home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1995 November / EnigmA AMIGA RUN 02 (1995)(G.R. Edizioni)(IT)[!][issue 1995-11][Skylink CD].iso / earcd / util / misc / random.lzh / random.c next >
C/C++ Source or Header  |  1995-09-15  |  2KB  |  85 lines

  1. /*
  2.  * Random
  3.  * by K.Veijalainen <veijalai@cc.lut.fi>
  4.  * 
  5.  * Reads in lines from stdin, scrambles their order and then outputs them.
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <time.h>
  11.  
  12. #define VERSION "v1.0"
  13.  
  14. #define DEFAULT_BUFFER_SIZE 8192
  15.  
  16. struct line_s {
  17.     struct line_s *next;
  18.     unsigned char *text;
  19. };
  20. struct line_s *firstline=NULL;
  21.  
  22.  
  23. int main(int argc, char **argv) {
  24.     unsigned char *buffer,*tb;
  25.     struct line_s *curline=NULL;
  26.     char *mark;
  27.     int n=0,l,r,x,len=DEFAULT_BUFFER_SIZE,prevpos=0,pos=0;
  28.  
  29.     buffer=malloc(DEFAULT_BUFFER_SIZE);
  30.     
  31.     srandom((unsigned int)time(NULL));
  32.     
  33.     /* Read everything */
  34.     while(!(feof(stdin))) {
  35.         /* Malloc space for new line entry.*/
  36.         *(buffer+pos)=getchar();
  37.         /* If we ran out of space, make the buffer larger.*/
  38.         if((pos-prevpos)>=(len-2)) {
  39.             tb=realloc(buffer,2*len);
  40.             len*=2;
  41.             buffer=tb;
  42.         }
  43.           
  44.         /* Another line read */
  45.         if(*(buffer+pos)==10) {
  46.             if(n==0) 
  47.               firstline=curline=malloc(sizeof(struct line_s));
  48.             else {
  49.                 curline->next=malloc(sizeof(struct line_s));
  50.                 curline=curline->next;
  51.             }
  52.             curline->next=NULL;
  53.             /* Malloc space for a string and copy it there.*/        
  54.             curline->text=malloc(pos-prevpos+2);
  55.             strcpy(curline->text,buffer+prevpos);
  56.             /* Inc line count */
  57.             ++n;
  58.             /* Mark beginning of new blah.*/
  59.             prevpos=pos+1;
  60.         }
  61.         /* Move to next char */
  62.         ++pos;
  63.     }
  64.     
  65.     /* This is for on/off "marks" that are used later.*/
  66.     mark=calloc(n,1);
  67.     
  68.     /* Output lines in random order.*/
  69.     r=random()%n;
  70.     for(l=0;l<n;l++) {
  71.         /* Select random line that is not yet printed.*/
  72.         while(*(mark+r))
  73.           r=random()%n;
  74.         *(mark+r)=1;
  75.         /* Seek the line data from the linked list.*/
  76.         curline=firstline;
  77.         for(x=0;x!=r;x++)
  78.           curline=curline->next;
  79.         /* Duubadsadsadas!*/
  80.         printf("%s",curline->text);
  81.     }
  82.     
  83.     exit(0);
  84. }
  85.